import { http } from '@/server'
import { getLocalStorage, setLocalStorage } from '@/storage'
import { Toast } from 'antd-mobile'
import { useCallback, useEffect, useState } from 'react'

export const useSMS = () => {
    const [countdown, setCountdown] = useState<number>(0)
    const isSending = countdown > 0

    useEffect(() => {
        const smsTime = Number(getLocalStorage('SMS_TIME') ?? 0)
        if (smsTime === 0) return
        const timeDiff = (new Date().getTime() - smsTime) / 1000
        if (timeDiff < 60) {
            setTimeout(() => {
                setCountdown(Number((60 - timeDiff).toFixed(0)))
            })
        }
    }, [])

    const sendSMS = useCallback(async (mobile: string, scene?: string) => {
        try {
            await http.post('/resource/send-code', { mobile, scene })
            setLocalStorage('SMS_TIME', new Date().getTime())
            setCountdown(60)
            Toast.show({ icon: 'success', content: '验证码已发送' })
        } catch {
            setCountdown(3)
        }
    }, [])

    useEffect(() => {
        let timer: NodeJS.Timeout | null = null

        if (countdown > 0) {
            timer = setTimeout(() => {
                setCountdown(prevCount => prevCount - 1)
            }, 1000)
        }

        return () => {
            timer && clearTimeout(timer)
        }
    }, [countdown, isSending])

    return { isSending, countdown, sendSMS }
}
